#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time    : 2020/9/21 5:44 下午
# @Author  : HuiDong.Bai
# @Email   : huidong.bai@ximalaya.com
# @File    : SerialReader.py
# @Software: PyCharm
import os
from threading import currentThread

import serial
import serial.tools.list_ports
import platform


def serial_com():
    if platform.system() == 'Windows':
        port_list = list(serial.tools.list_ports.comports())
        port_list_name = []
        if len(port_list) <= 0:
            print("串口设备为空，请检查!")
        else:
            for each_port in port_list:
                port_list_name.append(each_port[0])
        return port_list_name[0]
    else:
        return os.popen('ls /dev/tty.*usbserial*').readline().strip()


def get_serial(com_port):
    # 打开串口，并得到串口对象
    s = serial.Serial(com_port, '115200', timeout=4)
    # 判断是否打开成功
    if not s.is_open:
        s = -1
        print('打开串口失败')
        return s
    return s


def log_read(signal):
    com = serial_com()
    ser = get_serial(com)

    t = currentThread()
    while getattr(t, "open", True):
        log = ser.readline().replace(b'\\\\x', b'%').decode("UTF-8", "ignore").strip()
        if len(log):
            signal.log_print.emit(log)
